package Test;

import java.util.Arrays;

public class Heap {

    public int elem[];
    public int usedSize;

    public Heap() {
    }

    public Heap(int[] elem) {
        this.elem = new int[10];
    }

    public void initElem(int[] array) {
        for (int i = 0; i < array.length; i++) {
            elem[i] = array[i];
            usedSize++;

        }
    }

   /* public void creatHeap() {
        for (int parent = (usedSize - 1 - 1) / 2; parent >= 0; parent--) {
            siftDown(parent, usedSize);
        }
    }

    public void siftDown(int parent, int end) {
        int child = (parent * 2) + 1;
        while (child < end) {
            if (child + 1 < usedSize && elem[child] < elem[child + 1]) {
                child++;
            }
            if (elem[child] > elem[parent]) {
                swap(child, parent);
                parent=child;
                child=parent*2+1;
            } else {
                break;
            }


        }


    }*/
    public void creatHeap() {
        for (int parent = (usedSize-1-1)/2; parent >= 0; parent--) {
            siftDown(parent, usedSize);
        }
    }

    private void siftDown(int parent,int end) {
        int child = 2*parent+1;
        while (child < end) {
            if(child + 1 < usedSize && elem[child] < elem[child+1]) {
                child++;
            }
            //child一定是 左右孩子最大值的下标
            if(elem[child] > elem[parent]) {
                //交换
                swap(child,parent);
                parent = child;
                child = 2*parent+1;
            }else {
                break;
            }
        }
    }
    private void swap(int i,int j) {
        int tmp = elem[i];
        elem[i] = elem[j];
        elem[j] = tmp;
    }

   /* public void swap(int i, int j) {
        int tmp = elem[i];
        elem[i] = elem[j];
        elem[j] = tmp;
    }*/

    public int poll() {
        int tmp = elem[0];
        swap(0, usedSize - 1);
        usedSize--;
        siftDown(0, usedSize);
        return tmp;
    }

    public int offer(int val) {
        if (isFull()) {
            elem = Arrays.copyOf(elem, elem.length * 2);
        }
        elem[usedSize] = val;
        usedSize++;
        siftUp(usedSize);

        return 0;
    }

    public boolean isFull() {
        return usedSize == elem.length;
    }

    public void siftUp(int child) {
        int parent = (child - 1 - 1) / 2;
        while (child > 0) {
            if (elem[child] > elem[parent]) {
                swap(child, parent);
                child = parent;
                parent = (child - 1) / 2;
            } else {
                break;
            }
        }

    }

    public void HeapSort() {

        int end=usedSize-1;
        while (end>0){
            swap(0,end);
            siftDown(0,end-1);
            end--;

        }

    }
}